package quick.portal.service;

import java.io.IOException;

import com.alibaba.fastjson.JSON;
import com.squareup.okhttp.Request;

import quick.common.AppContext;
import quick.common.UIHelper;
import quick.communication.AsyncHttpResponseHandler;
import quick.communication.HttpClient;
import quick.communication.RequestParams;
import quick.portal.data.APIResult;
import quick.portal.data.AppInfo;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;

public class AppInfoService extends BaseService {
	
	private int versionCode = -1;
	private String versionName = "";
	
	public int getVersionCode()
	{
		return this.versionCode;
	}
	
	public String getVersionName()
	{
		return this.versionName;
	}
	
    public AppInfoService()
    {
        try 
        {
        	Context context = AppContext.getInstance();
        	String packageName = context.getPackageName();
        	
        	PackageInfo info = context.getPackageManager().getPackageInfo(packageName, 0);
        	this.versionCode = info.versionCode;
        	this.versionName = info.versionName;
            
        } 
        catch (NameNotFoundException e) 
        {
        	//
        }
    }
    
    public void updateApp()
    {
    	final Context context = AppContext.getInstance();
    	
    	if(versionCode<=0)
    	{
    		UIHelper.ToastMessage(context,"版本信息错误，无法更新");
    		return;
    	}
    	
    	RequestParams params = this.getParams().AddParam("VersionCode", String.valueOf(versionCode));
		
		HttpClient.get(api_url+"NewVersionApp", params, new AsyncHttpResponseHandler() {
			@Override
            public void onSuccess(String body) {

                APIResult result = JSON.parseObject(body, APIResult.class);
    			
    			if(result.getReturnCode()<0)
	        	{
    				UIHelper.ToastMessage(context,"没有要更新的版本");
					return;
	        	}
    			
    			AppInfo app = JSON.parseObject(result.getBody(), AppInfo.class);
    			
    			String url = portal_url + "Systems/AppInfo/DownloadApp/";
    			String token = AppContext.getInstance().getToken();
    	    	url = url + "?" + AppContext.Login_Token_Key + "=" + token;
    			
    			Intent service = new Intent(AppContext.getInstance(),AppUpdateService.class);
    			service.putExtra("Url", url);
    			service.putExtra("AppName", app.getName());
    			AppContext.getInstance().startService(service);
    			
    			
        	}
        	
        	@Override
            public void onFailure(Request request, IOException e) {
        		UIHelper.ToastMessage(context,"版本更新失败：" + e.getMessage());
            }
		});
    }
}
